//! 数据模型定义模块
//!
//! 该模块负责处理Schema定义，包含Model、Table和Field的定义

use serde::{Deserialize, Serialize};
use anyhow::{anyhow, Result};

/// Schema模型定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Schema {
    /// 模型名称
    pub name: String,
    /// 模型注释
    pub comment: String,
    /// 表定义列表
    pub tables: Vec<Table>,
}

/// 表定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Table {
    /// 表名称
    pub name: String,
    /// 表注释
    pub comment: String,
    /// 字段定义列表
    pub fields: Vec<Field>,
}

/// 字段定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Field {
    /// 字段名称
    pub name: String,
    /// 字段注释
    pub comment: String,
    /// 字段角色
    pub role: FieldRole,
    /// 字段类型
    #[serde(rename = "type")]
    pub field_type: FieldType,
    /// 是否为索引字段
    #[serde(default)]
    pub index: bool,
    /// 精度
    #[serde(default)]
    pub precision: Option<u32>,
    /// 小数位数
    #[serde(default)]
    pub scale: Option<u32>,
    /// 默认值
    #[serde(default)]
    pub default: Option<serde_json::Value>,
    /// 表达式字段
    #[serde(default, rename = "exprField")]
    pub expr_field: Option<String>,
    /// 默认表达式
    #[serde(default, rename = "defaultExpr")]
    pub default_expr: Option<String>,
    /// 外键引用
    #[serde(default)]
    pub references: Option<String>,
    /// 删除级联规则
    #[serde(default, rename = "onDelete")]
    pub on_delete: Option<String>,
    /// 更新级联规则
    #[serde(default, rename = "onUpdate")]
    pub on_update: Option<String>,
}

/// 字段角色枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum FieldRole {
    /// 主键字段
    #[serde(rename = "PRIMARY")]
    Primary,
    /// 外键字段
    #[serde(rename = "FOREIGN")]
    Foreign,
    /// 普通存储字段
    #[serde(rename = "NORMAL")]
    Normal,
    /// 计算字段
    #[serde(rename = "FORMULA")]
    Formula,
}

/// 字段类型枚举
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum FieldType {
    /// 整数类型
    #[serde(rename = "INT")]
    Int,
    /// 浮点数类型
    #[serde(rename = "FLOAT")]
    Float,
    /// 可变长度字符串
    #[serde(rename = "VARCHAR")]
    Varchar,
    /// 长文本类型
    #[serde(rename = "TEXT")]
    Text,
    /// 枚举类型
    #[serde(rename = "ENUM")]
    Enum,
    /// 日期类型
    #[serde(rename = "DATE")]
    Date,
    /// 日期时间类型
    #[serde(rename = "DATETIME")]
    DateTime,
    /// 数组类型
    #[serde(rename = "ARRAY")]
    Array,
    /// 映射类型
    #[serde(rename = "MAP")]
    Map,
}

impl Schema {
    /// 从JSON字符串解析Schema
    pub fn from_json(json: &str) -> Result<Self, anyhow::Error> {
        let schema: Schema = serde_json::from_str(json)?;
        schema.validate()?;
        Ok(schema)
    }
    
    /// 验证Schema定义
    pub fn validate(&self) -> Result<(), anyhow::Error> {
        // 验证模型名称
        if !is_valid_name(&self.name) {
            return Err(anyhow!("Invalid schema name: {}", self.name));
        }

        // 验证表定义
        let mut table_names = std::collections::HashSet::new();
        for table in &self.tables {
            // 检查表名是否重复
            if !table_names.insert(table.name.clone()) {
                return Err(anyhow!("Duplicate table name: {}", table.name));
            }
            
            // 验证表定义
            table.validate()?;
        }
        
        Ok(())
    }
    
    /// 生成数据库表结构
    pub fn generate_table_structure(&self) -> Result<String, anyhow::Error> {
        // 这里应该实现生成数据库表结构的逻辑
        // 目前先返回空字符串
        Ok(String::new())
    }
}

impl Table {
    /// 验证表定义
    pub fn validate(&self) -> Result<(), anyhow::Error> {
        // 验证表名称
        if !is_valid_name(&self.name) {
            return Err(anyhow!("Invalid table name: {}", self.name));
        }

        // 验证字段定义
        let mut field_names = std::collections::HashSet::new();
        let mut primary_keys = 0;
        
        for field in &self.fields {
            // 检查字段名是否重复
            if !field_names.insert(field.name.clone()) {
                return Err(anyhow!("Duplicate field name: {} in table: {}", field.name, self.name));
            }
            
            // 验证字段定义
            field.validate()?;
            
            // 统计主键数量
            if field.role == FieldRole::Primary {
                primary_keys += 1;
            }
        }
        
        // 检查是否只有一个主键
        if primary_keys != 1 {
            return Err(anyhow!("Table {} must have exactly one primary key, found: {}", self.name, primary_keys));
        }
        
        Ok(())
    }
}

impl Field {
    /// 验证字段定义
    pub fn validate(&self) -> Result<(), anyhow::Error> {
        // 验证字段名称
        if !is_valid_name(&self.name) {
            return Err(anyhow!("Invalid field name: {}", self.name));
        }

        // 根据角色验证字段
        match self.role {
            FieldRole::Primary => {
                // 主键字段必须是INT或VARCHAR类型
                if self.field_type != FieldType::Int && self.field_type != FieldType::Varchar {
                    return Err(anyhow!("Primary key field {} must be INT or VARCHAR type", self.name));
                }
                
                // 主键字段不支持表达式
                if self.expr_field.is_some() || self.default_expr.is_some() {
                    return Err(anyhow!("Primary key field {} cannot have expression", self.name));
                }
            },
            FieldRole::Foreign => {
                // 外键字段必须有引用
                if self.references.is_none() {
                    return Err(anyhow!("Foreign key field {} must have references", self.name));
                }
                
                // 外键字段不支持表达式
                if self.expr_field.is_some() || self.default_expr.is_some() {
                    return Err(anyhow!("Foreign key field {} cannot have expression", self.name));
                }
            },
            FieldRole::Formula => {
                // 计算字段必须有默认表达式或表达式字段
                if self.default_expr.is_none() && self.expr_field.is_none() {
                    return Err(anyhow!("Formula field {} must have defaultExpr or exprField", self.name));
                }
            },
            FieldRole::Normal => {
                // 普通字段不支持表达式（除非是ARRAY或MAP类型）
                if (self.expr_field.is_some() || self.default_expr.is_some()) 
                    && (self.field_type != FieldType::Array && self.field_type != FieldType::Map) {
                    return Err(anyhow!("Normal field {} can only have expression if it's ARRAY or MAP type", self.name));
                }
            }
        }
        
        // 验证精度和小数位数
        if let Some(precision) = self.precision {
            if precision == 0 {
                return Err(anyhow!("Precision of field {} must be greater than 0", self.name));
            }
        }
        
        if let Some(scale) = self.scale {
            if let Some(precision) = self.precision {
                if scale > precision {
                    return Err(anyhow!("Scale of field {} cannot be greater than precision", self.name));
                }
            } else {
                return Err(anyhow!("Field {} has scale but no precision", self.name));
            }
        }
        
        Ok(())
    }
}

/// 验证名称是否符合规范（英文字母+数字，首字母大写）
fn is_valid_name(name: &str) -> bool {
    if name.is_empty() {
        return false;
    }
    
    let chars: Vec<char> = name.chars().collect();
    
    // 首字母必须大写
    if !chars[0].is_ascii_uppercase() {
        return false;
    }
    
    // 只能包含英文字母和数字
    for c in chars {
        if !c.is_ascii_alphanumeric() {
            return false;
        }
    }
    
    true
}